import { Component } from 'react';
import styles from './index.module.scss';
// 1 在 src/index.js 中全局导入 antd 的样式文件
import 'antd/dist/antd.css';
import { Card, Form, Input, Button, Checkbox, message } from 'antd';
import logo from 'assets/logo.png';
import { getCode, login } from 'api/user';
import { setToken } from 'utils/storage';
export default class Login extends Component {
  // 登录按钮
  onFinsh = async (val) => {
    // console.log(val);
    try {
      const res = await login(val);
      // console.log(res);
      // localStorage.setItem('geek-part', res.data.token);
      setToken(res.data.token);
      message.success('登录成功', 1);
      this.props.history.push('/layout');
    } catch (error) {
      // console.dir(error);
      if (error.response) {
        message.warning(error.response.data.message);
      }
    }
  };
  // 发送验证码
  sendCode = async (mobile) => {
    const res = await getCode('13566667777');
    console.log(res);
  };
  render() {
    return (
      <div className={styles['login']}>
        <Card className="login-container">
          <img src={logo} alt="" className="login-logo" />
          <Form
            name="basic"
            autoComplete="off"
            onFinish={this.onFinsh}
            initialValues={{
              mobile: '13911111111',
              code: '246810',
              agree: true,
            }}
          >
            <Form.Item
              name="mobile"
              rules={[
                { required: true, message: '请输入用户名' },
                {
                  pattern: /^[1][3,4,5,7,8][0-9]{9}$/,
                  message: '请输入11位数的手机号',
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="code"
              rules={[
                { required: true, message: '请输入验证码' },
                { max: 6, message: '验证码最多6位数' },
              ]}
            >
              <Input
                addonAfter={
                  <Button
                    onClick={() => {
                      this.sendCode();
                    }}
                  >
                    发送验证码
                  </Button>
                }
              />
            </Form.Item>
            {/* valuePropName表示把checked作为值 */}
            <Form.Item
              name="agree"
              valuePropName="checked"
              rules={[
                {
                  validator: (_, value) =>
                    value
                      ? Promise.resolve()
                      : Promise.reject(new Error('请阅读并同意用户协议')),
                },
              ]}
            >
              <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button block type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    );
  }
}
